﻿using AutoMapper;
using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Darius.API.Application.Commands
{
    public class RoleSearchHandler : IRequestHandler<RoleSearchCommand, Result>
    {
        private readonly IBaseRepositorys<Roles> roleRepository;
        private readonly ILogger<RoleCreateHandler> logger;

        public RoleSearchHandler(IBaseRepositorys<Roles> roleRepository, ILogger<RoleCreateHandler> logger)
        {
            this.roleRepository = roleRepository;

            this.logger = logger;
        }
        /// <summary>
        /// 角色查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(RoleSearchCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CodeEnum.search };
                var list = roleRepository.GetAll().Where(x => x.Pid == 0).ToList();
                List<Cascard> cascards = new List<Cascard>();
                foreach (var item in list)
                {
                    Cascard cascard = new Cascard();
                    cascard.value = item.RoleId;
                    cascard.label = item.RoleName;
                    cascard.DepartmentName = item.DepartmentName;
                    cascard.StartUp = item.StartUp;
                    cascard.Pid = item.Pid;
                    cascard.children = GetCascards(item.RoleId);
                    cascards.Add(cascard);
                }
                result.Data = cascards;
                result.Messege = "角色查询成功";
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "角色查询失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = ex.Message };
       
            }

        }
        /// <summary>
        /// 级联
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public List<Cascard> GetCascards(int pid = 0)
        {
            var list = roleRepository.GetAll().Where(x => x.Pid == pid).ToList();
            List<Cascard> cascards = new List<Cascard>();
            foreach (var item in list)
            {
                Cascard cascard = new Cascard();
                cascard.value = item.RoleId;
                cascard.label = item.RoleName;
                cascard.DepartmentName = item.DepartmentName;
                cascard.StartUp = item.StartUp;
                cascard.Pid = item.Pid;
                cascard.children = GetCascards(item.RoleId);
                cascards.Add(cascard);
            }
            return cascards;
        }
    }
}
